// Fill out your copyright notice in the Description page of Project Settings.


#include "OpenableBox.h"
#include "Components/BoxComponent.h"

// Sets default values
AOpenableBox::AOpenableBox()
{
 	// Set this actor to call Tick() every frame.  You can turn this off to improve performance if you don't need it.
	PrimaryActorTick.bCanEverTick = false;

	Scene = CreateDefaultSubobject<USceneComponent>(TEXT("Scene"));
	Scene->SetupAttachment(RootComponent);

	BoxMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("Box"));
	TopMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("Top"));

	BoxMesh->SetupAttachment(Scene);
	TopMesh->SetupAttachment(Scene);
}

// Called when the game starts or when spawned
void AOpenableBox::BeginPlay()
{
	Super::BeginPlay();
	FRotator BoxRotate(0, 0, -60 * fOpenPersent);
	TopMesh->SetRelativeRotation(BoxRotate);
}

// Called every frame
void AOpenableBox::Tick(float DeltaTime)
{
	Super::Tick(DeltaTime);

}

 void AOpenableBox::OpenBox() {
	 if (!bIsAnimating)
	 {
		 GetWorld()->GetTimerManager().SetTimer(TimerHandleOpen, this, &AOpenableBox::OpenByPresent, 0.01f, true);
		 bIsAnimating = true;
		 bIsOpened = true;
	 }
}

 void AOpenableBox::OpenByPresent() {
	if (fOpenPersent >=1)
	{
		GetWorld()->GetTimerManager().ClearTimer(TimerHandleOpen);
		bIsAnimating = false;
	}
	else
	{
		fOpenPersent += 1 / (fOpenTime*100);
		FRotator BoxRotate(0,0,-60* fOpenPersent);
		TopMesh->SetRelativeRotation(BoxRotate);
	}
}

 void AOpenableBox::CloseBox() {
	 if (!bIsAnimating)
	 {
		 GetWorld()->GetTimerManager().SetTimer(TimerHandleClose, this, &AOpenableBox::CloseByPresent, 0.01f, true);
		 bIsAnimating = true;
	 }
 }

 void AOpenableBox::CloseByPresent() {
	 if (fOpenPersent <=0)
	 {
		 GetWorld()->GetTimerManager().ClearTimer(TimerHandleClose);
		 bIsAnimating = false;
	 }
	 else
	 {
		 fOpenPersent = fOpenPersent-1 / (fCloseTime * 100);
		 FRotator BoxRotate(0, 0, -60 * fOpenPersent);
		 TopMesh->SetRelativeRotation(BoxRotate);
	 }
 }